<template>
  <div class="business_report_analyse" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" initShow="month" :query="query" :isShowCon="false"></date-time>
            <el-button type="primary" class="primary_btn fr find" v-on:click.stop="search">{{
              $t('public.search2')
            }}</el-button>
            <div class="clear"></div>
          </div>
        </div>
      </div>

      <affix :label="title"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{ $t('report.hicharsNotes') }}: <span></span>{{ $t('report.hicharsLight') }}</span>
          <span class="dark"><span></span>{{ $t('report.hicharsDark') }}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">
          <el-button class="primary_btn fr" v-on:click.stop="config" v-if="!configHeaderBool">{{
            $t('report.setHeaderConfig')
          }}</el-button>

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn" @click.stop="exportXlsx">{{
            $t('report.exportXls')
          }}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{ $t('report.exportPDF') }}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{ $t('report.toggleInstructe') }}</span>
              </template>
              <div>
                {{ $t('report.creatBusinessNumber') }} <br />
                {{ $t('report.finishBusinessNumber') }} <br />
                {{ $t('report.finishRate') }} <br />
                {{ $t('report.averFinishTime') }} <br />
                {{ $t('report.aveDealTime') }} <br />
                {{ $t('report.averWaitTime') }} <br />
                {{ $t('report.busiRepAnalyseTip8') }} <br />
                {{ $t('report.busiRepAnalyseTip9') }} <br />
                {{ $t('report.busiRepAnalyseTip10') }} <br />
                {{ $t('report.busiRepAnalyseTip11') }} <br />
                {{ $t('report.busiRepAnalyseTip12') }} <br />
                {{ $t('report.busiRepAnalyseTip13') }} <br />
                {{ $t('report.busiRepAnalyseTip14') }} <br />
                {{ $t('report.busiRepAnalyseTip15') }}
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="tableData" :config="headOptions.Config"></report-table>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      modal-append-to-body
      lock-scroll
      top="10%"
      :title="$t('report.reportExportHelp')"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <span>{{ $t('report.reportExportTipTitle') }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{ $t('public.cancel') }}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{ $t('public.confirm') }}</el-button>
      </span>
    </el-dialog>
    <header-option
      v-show="isShow"
      :show="isShow"
      :option="headOptionsShow"
      type="business_report_analyse"
      v-on:close="close"
    ></header-option>
  </div>
</template>
<script>
import affix from '../../../ui-modules/affix/Affix.vue'
import dateTime from '../base/datetime.vue'
import reportTable from '../base/reportTable.vue'
import { deepClone, getFormatTimeBySecond, optionTimeTypeCheck } from '@/utils/m7Utils.js'
import {
  exportReportPdf,
  checkTime,
  searchTime,
  colorConfigArr,
  headOptionsToXlsxHeaders
} from '@/utils/reportUtils.js'
import headerOption from '../base/headerOption.vue'
import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
export default {
  name: 'business_report_analyse',
  data() {
    return {
      id: 'business_report_analyse', // 查询传的id
      title: this.$t('report.businessReportAnalyse'),
      loading: false,
      query: {}, // 查询条件
      headOptionsShow: {}, // 配置表头传入的对象
      isShow: false, // 配置表头开关
      dialogVisible: false, // 导出pdf弹窗开关
      selectedAgentList: [], // 座席选择绑定的值
      businessFlowOptions: [], // 工单类型集合
      serverData: [], // 返回的数据
      headOptions: { Config: [], data: [] }, // 表头数据
      highchartsDefaultOptions: {
        chart: { type: 'column', animation: false },
        colors: colorConfigArr,
        xAxis: {
          categories: [],
          title: {
            enabled: true,
            text: '',
            style: { fontWeight: 'normal' }
          }
        },
        yAxis: {
          gridLineColor: '#e6e6e6',
          allowDecimals: false,
          title: { text: '' },
          showEmpty: false
        },
        title: { text: this.$t('report.businessReportAnalyse') },
        legend: { align: 'center', verticalAlign: 'top', y: 30 },
        tooltip: {
          pointFormat:
            '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
          shared: true
        },
        credits: { enabled: false },
        series: []
      }
    }
  },
  components: {
    affix,
    dateTime,
    reportTable,
    headerOption
  },
  computed: {
    // 是否展示配置表头
    configHeaderBool() {
      return this.$store.state.report.setConfigHeaderBool
    },
    tableData() {
      return this.getTableData(this.serverData, this.headOptions)
    },
    totalData() {
      if (!this.serverData || this.serverData.length === 0) {
        return [{ flow: this.$t('report.total') }]
      }

      let headerConfig = this.headOptions.Config || []
      let datas = this.serverData
      let total = {
        flow: this.$t('report.total'),
        finish: 0,
        finishTimeCount: 0,
        processCount: 0,
        processTimeCount: 0,
        waitTimeCount: 0,
        pickCount: 0
      }

      for (let i = 0; i < headerConfig.length; i++) {
        for (let j = 0; j < datas.length; j++) {
          if (!isNaN(datas[j][headerConfig[i].name])) {
            if (headerConfig[i].name in total === false) {
              total[headerConfig[i].name] = 0
            }
            total[headerConfig[i].name] += datas[j][headerConfig[i].name]
          }

          if (headerConfig[i].name === 'finishTimeAvg') {
            total.finishTimeCount += datas[j]['finishTimeCount']
          } else if (headerConfig[i].name === 'processTimeAvg') {
            total.processTimeCount += datas[j]['processTimeCount']
            total.processCount += datas[j]['processCount']
          } else if (headerConfig[i].name === 'waitTimeAvg') {
            total.waitTimeCount += datas[j]['waitTimeCount']
            total.pickCount += datas[j]['pickCount']
          }
        }
      }

      // 完成率
      total.finishRate = total.create > 0 ? ((total.finish * 100) / total.create).toFixed(0) : 0
      // 平均完成时长
      total.finishTimeAvg = total.finish > 0 ? Math.round(total.finishTimeCount / total.finish) : 0
      total.finishTimeAvg = getFormatTimeBySecond(total.finishTimeAvg)
      // 平均处理时长
      total.processTimeAvg = total.processCount > 0 ? Math.round(total.processTimeCount / total.processCount) : 0
      total.processTimeAvg = getFormatTimeBySecond(total.processTimeAvg)
      // 平均等待时长
      total.waitTimeAvg = total.pickCount > 0 ? Math.round(total.waitTimeCount / total.pickCount) : 0
      total.waitTimeAvg = getFormatTimeBySecond(total.waitTimeAvg)

      return [total]
    },
    highchartsOptions() {
      let options = deepClone(this.highchartsDefaultOptions)
      if (!this.serverData || this.serverData.length === 0) {
        return options
      }

      let headerConfig = this.headOptions.Config || []
      let datas = this.serverData
      let categoriesArray = []
      let seriesArray = []

      headerConfig.forEach((item) => {
        if (!item.show) {
          return
        }
        if (item.name === 'flow') {
          return
        }
        let serie = { name: item.displayname, data: [], valueName: item.name }
        if (item.name === 'finishTimeAvg' || item.name === 'processTimeAvg' || item.name === 'waitTimeAvg') {
          serie.tooltip = { valueSuffix: 's' }
        } else if (
          item.name === 'finishRate' ||
          item.name === 'createAndFinshRate' ||
          item.name === 'finishTimeOutCountRate' ||
          item.name === 'finishWithin24HoursRate' ||
          item.name === 'finishWithin48HoursRate'
        ) {
          serie.tooltip = { valueSuffix: '%' }
        }
        seriesArray.push(serie)
      })

      for (let i = 0; i < datas.length; i++) {
        categoriesArray.push(this.getBusinessFlowName(datas[i].flow))
        for (let j = 0; j < seriesArray.length; j++) {
          seriesArray[j].data.push(datas[i][seriesArray[j].valueName])
        }
      }

      options.xAxis.categories = categoriesArray
      options.series = seriesArray
      console.log(options)
      debugger
      return options
    }
  },
  methods: {
    getTableData(serverData, headOptions) {
      if (!serverData || serverData.length === 0) {
        return []
      }

      let data = deepClone(serverData)
      data.forEach((item) => {
        item.flow = this.getBusinessFlowName(item.flow)
        headOptions.Config.forEach((option, index) => {
          if (option.name.indexOf('Rate') > -1 && option.displayname.indexOf('率') > -1) {
            item[option.name] = `${item[option.name]}%`
          }
          if (option.timeType && option.timeType === 'hhmmss') {
            item[option.name] = getFormatTimeBySecond(item[option.name])
          } else if (option.timeType && option.timeType === 'second') {
            item[option.name] = item[option.name] + 's'
          }
        })
      })

      return data
    },
    getBusinessFlowName(id) {
      for (let i = 0; i < this.businessFlowOptions.length; i++) {
        if (this.businessFlowOptions[i].value === id) {
          return this.businessFlowOptions[i].label
        }
      }
      return ''
    },
    getSearchQueryData() {
      let data = {
        reportType: this.id,
        account: this.$store.state.session.user.account,
        query: { reportType: this.id },
        user: {
          type: this.$store.state.session.user.type,
          moduleUsers: this.$store.state.session.user.moduleUsers
        }
      }
      let query = deepClone(this.query)
      if (query.timeType === 'other') {
        // 校验类型与时间
        let message = checkTime(query.StartTime, query.EndTime, false, true)
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
        let StartTimeStr = query.StartTime.replace(/-/g, '')
        query.StartTime = StartTimeStr
        let EndTimeStr = query.EndTime.replace(/-/g, '')
        query.EndTime = EndTimeStr
      }
      if (this.selectedAgentList.length > 0) {
        query.selectedAgentList = this.selectedAgentList.join(',')
      }
      data.query = Object.assign({}, data.query, query)
      return data
    },
    search() {
      var data = this.getSearchQueryData()
      if (!data) {
        return
      }
      this.loading = true
      this.$store.dispatch('queryBusinessAnalyseReport', data).then((res) => {
        if (!res.success) {
          this.loading = false
          return
        }
        // 表头
        this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)

        this.serverData = deepClone(res.data) || this.serverData
        this.loading = false
      })
    },
    exportXlsx() {
      var data = this.getSearchQueryData()
      if (!data) {
        return
      }
      this.loading = true
      this.$store.dispatch('queryBusinessAnalyseReport', data).then((res) => {
        if (!res.success) {
          this.loading = false
          return
        }
        this.loading = false
        var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || [])
        var serverData = deepClone(res.data) || []
        var tableData = this.getTableData(serverData, headOptions)

        var headers = headOptionsToXlsxHeaders(headOptions.Config)
        var dh = XlsxUtil.getDownloadHelper(headers, tableData)
        var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
        dh.download('工单整体分析报表' + timeStamp)
      })
    },
    exportXls() {
      let data = {
        Method: 'exportBusinessAnalyse',
        Query: { reportType: this.id, user: this.$store.state.session.user._id }
      }
      let query = deepClone(this.query)
      if (query.timeType === 'other') {
        let message = checkTime(query.StartTime, query.EndTime, false, true) // 校验类型与时间
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
        let StartTimeStr = query.StartTime.replace(/-/g, '')
        query.StartTime = StartTimeStr
        let EndTimeStr = query.EndTime.replace(/-/g, '')
        query.EndTime = EndTimeStr
      }
      if (this.selectedAgentList.length > 0) {
        query.selectedAgentList = this.selectedAgentList.join(',')
      }
      data.Query = Object.assign({}, data.Query, query)
      this.$store.dispatch('exportBusinessAnalyseReport', data)
    },
    exportPdf() {
      this.dialogVisible = true
    },
    confirm() {
      this.dialogVisible = false
      exportReportPdf({ title: this.$t('report.businessReportAnalyse') + searchTime(this.query), id: this.id })
    },
    //   配置 表头
    config() {
      this.$store.dispatch('getReportTableHeader', 'business_report_analyse').then((res) => {
        this.headOptionsShow = optionTimeTypeCheck(res)
        this.isShow = !this.isShow
      })
    },
    close(data) {
      this.isShow = false
      if (data === 'save') {
        this.search()
      }
    }
  },
  beforeMount() {
    this.$store.dispatch('getCache', { type: 'businessFlow' }).then((businessFlow) => {
      this.businessFlowOptions = businessFlow.map((flow) => ({ label: flow.name, value: flow._id }))
      this.search()
    })
  }
}
</script>
<style lang="stylus" scoped>
@import "../../../../assets/common.styl"
.business_report_analyse
  .tab
    .deploy
      .tip
        margin-left 40px
      .item
        cursor pointer
        &:hover
          color $c-main
  .ichars
    margin-top 20px
  .top
    .el-row
      padding-left 16px
  .deploy
    .te
      cursor pointer
</style>
